package com.demo.security.cloud.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * 配置OAuth2
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {

    /**
     * 配置令牌Token对资源访问的安全约束。对URL访问的安全
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {

        security // oauth/token_key 公开
                .tokenKeyAccess("permitAll()")
                // oauth/check_token 公开
                .checkTokenAccess("permitAll()")
                // 允许表单认证
                .allowFormAuthenticationForClients();
    }

    /**
     * 配置客户端详情，在这写入客户端信息或者其他。
     * 检测是不是配置好的客户端。
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        // 暂时使用内存方式
        clients.inMemory()
                // 客户端ID
                .withClient("c1")
                // 客户端密钥
//                .secret(new BCryptPasswordEncoder().encode("ABC"))
                .secret("ABC")
                // 资源列表
                .resourceIds("res1")
                // 该client允许的协议类型
                .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")
                // 授权范围标识 后续根据标识限制授权。
                .scopes("all")
                // false跳转到授权页面
                .autoApprove(false)
                // 验证通过后回调地址
                .redirectUris("https://www.baidu.com");
    }


    //配置令牌访问端点
    // 这里自动注入的类导致了必须有 （NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.env.Environment' available）
    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;

    /**
     * 暂时使用内存模式
     * @return
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices(){
        return new InMemoryAuthorizationCodeServices();
    }

    /**
     * 注入它，需要一个 UserDetailsService。这里使用自定义的 SpringDataUserDetailsService
     */
    @Autowired
    private AuthenticationManager authenticationManager;


    /**
     * 配置令牌Token访问端点和令牌服务
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints
                // 密码模式
                .authenticationManager(authenticationManager)
                // 授权码模式
                .authorizationCodeServices(authorizationCodeServices)
                // 令牌管理服务
                .tokenServices(tokenServices())
                // 是否重用refresh_token
                .reuseRefreshTokens(true)
                // POST需要
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }

    /**
     * 注入TokenStore
     */
    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private ClientDetailsService clientDetailsService;

    /**
     * Token生成的方式
     * @return
     */
    @Bean
    public AuthorizationServerTokenServices tokenServices(){
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setClientDetailsService(clientDetailsService);
        defaultTokenServices.setSupportRefreshToken(true);
        defaultTokenServices.setTokenStore(tokenStore);
        // 令牌默认有效期2小时
        defaultTokenServices.setAccessTokenValiditySeconds(7200);
        // 刷新令牌有效期3天
        defaultTokenServices.setRefreshTokenValiditySeconds(259200);

        return defaultTokenServices;
    }
}
